package com.lzp.badminton.controller;

import com.lzp.badminton.config.ResultMessage;
import com.lzp.badminton.model.User;
import com.lzp.badminton.service.FileUploadService;
import com.lzp.badminton.service.IUserService;
import com.lzp.badminton.util.loginUtil.ProductToken;
import com.lzp.badminton.util.validatecodeUtils.IVerifyCodeGen;
import com.lzp.badminton.util.validatecodeUtils.SimpleCharVerifyCodeGenImpl;
import com.lzp.badminton.util.validatecodeUtils.VerifyCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author astupidcoder
 * @since 2022-02-11
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private ResultMessage resultMessage;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private FileUploadService fileUploadService;
    @Autowired
    private ProductToken productToken;

    /**
     * 用户登陆
     * */
    @PostMapping(value = "/login")
    @ResponseBody
    public ResultMessage login(String username, String userpassword, String verifyCode, HttpServletRequest request, HttpSession session) {

        System.out.println(username+ " " + userpassword + " " + verifyCode);
        // 获取注册的验证码
        String vCode = (String) request.getServletContext().getAttribute("VerifyCode");

        System.out.println(vCode);


        if (!vCode.equals(verifyCode)) {
            resultMessage.fail("404","验证码有误");
        } else {
            User user = iUserService.login(username, userpassword);

            if (user != null) {
                String token = UUID.randomUUID().toString().replaceAll("-", "");
                Map result = new HashMap();
                result.put("userId", user.getUserId());
                result.put("userName", user.getUserName());
                result.put("nickName", user.getNickname());
                result.put("useravatar", user.getUserAvatar());
                result.put("token", token);

                Map<String, String> mapInfo = productToken.productToken(user.getUserId(), token);

                resultMessage.success("200", "登陆成功", result);
            } else {
                resultMessage.fail("404", "账号或密码错误");
            }
        }
        return resultMessage;
    }

    /**
     * 用户登出
     * */
    @PostMapping(value = "/logout")
    @ResponseBody
    public ResultMessage logout(@RequestParam("userid") String userid) {
        // 删除redis中保存的用户token
        redisTemplate.delete(userid);

        if (!redisTemplate.hasKey(userid)) {
            resultMessage.success("200", "登出成功");
        } else {
            resultMessage.fail("404", "登出失败");
        }
        return resultMessage;
    }

    /**
     * 判断用户是否登陆
     * */
    @RequestMapping(value = "/isUserLogin")
    @ResponseBody
    public ResultMessage isUserLogin(@RequestParam("userid") String userid) {

        if (redisTemplate.hasKey(userid)) {
            resultMessage.success("200", "用户处于登陆状态");
        } else {
            resultMessage.success("401", "用户未登录");
        }
        return resultMessage;
    }

    /**
     * 用户注册
     */
    @PostMapping(value = "/register")
    @ResponseBody
    public ResultMessage register(String username, String userpassword, String verifyCode, HttpServletRequest request) {

        // 获取注册的验证码
        String vCode = (String) request.getServletContext().getAttribute("VerifyCode");

        if (!vCode.equals(verifyCode)) {
            resultMessage.fail("1","验证码有误");
        } else {
            if (iUserService.addUser(username, userpassword)) {
                resultMessage.success("200", "注册成功");
            } else {
                resultMessage.fail("404", "注册失败");
            }
        }

        return resultMessage;
    }

    /**
     * 获得用户全部信息
     * */
    @GetMapping(value = "/getUserInfo")
    @ResponseBody
    public ResultMessage getUserInfo(@RequestParam("userid") String userid){
        User user = iUserService.getUserInfoByUserId(userid);
        if (user != null) {
            resultMessage.success("200", "用户信息获取成功",user);
            return resultMessage;
        } else {
            resultMessage.fail("404", "用户信息获取失败");
            return resultMessage;
        }
    }

    /**
     * 获得用户头像
     * */
    @GetMapping(value = "/getUserAvatar")
    @ResponseBody
    public ResultMessage getUserAvatar(@RequestParam("username") String username){
        String user_avatar = iUserService.getUserAvatarByUsername(username);
        if (!user_avatar.equals("")) {
            resultMessage.success("200", "用户头像获取成功", user_avatar);
            return resultMessage;
        } else {
            resultMessage.fail("404", "用户头像获取失败");
            return resultMessage;
        }
    }

    /**
     * 判断用户名是否已存在
     */
    @GetMapping(value = "/getUserExit")
    @ResponseBody
    public ResultMessage getUserExit(@RequestParam("username") String username){
        User user = iUserService.findUserByUserName(username);
        if (user != null) {
            resultMessage.success("200", "用户名存在");
            return resultMessage;
        } else {
            resultMessage.fail("404", "用户名不存在");
            return resultMessage;
        }
    }

    /**
     * 生成验证码
     * */
    @GetMapping("/verifyCode")
    public void verifyCode(HttpServletRequest request, HttpServletResponse response) {
        IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();
        try {
            //设置长宽
            VerifyCode verifyCode = iVerifyCodeGen.generate(80, 28);
            String code = verifyCode.getCode();

            //将VerifyCode绑定session
            //request.getSession().setAttribute("VerifyCode", code);
            request.getServletContext().setAttribute("VerifyCode", code);
            //设置响应头
            response.setHeader("Pragma", "no-cache");
            //设置响应头
            response.setHeader("Cache-Control", "no-cache");
            //在代理服务器端防止缓冲
            response.setDateHeader("Expires", 0);
            //设置响应内容类型
            response.setContentType("image/jpeg");
            response.getOutputStream().write(verifyCode.getImgBytes());
            response.getOutputStream().flush();
        } catch (IOException e) {}
    }
}
